<?php


namespace App\Http\Controllers\Admin\Maintain;

use App\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DatabaseController extends AdminController
{

    public function data(Request $request)
    {
        $list = array_map('array_change_key_case', array_map('get_object_vars', DB::select('SHOW TABLE STATUS')));
        if ($keywords = $request->get('keywords')) {
            $keywords = filterStr($keywords);
            $list = collect($list)->filter(function ($item) use ($keywords) {
                return (bool)strstr($item['name'], $keywords);
            })->all();
        }
        return $this->succeed([
            'rows' => $list
        ]);
    }

    public function show(Request $request)
    {
        $data = [];
        if ($table = $request->get('table')) {
            $data = array_map('array_change_key_case', array_map('get_object_vars', DB::select("SHOW FULL COLUMNS FROM `{$table}`")));
        }
        return $this->succeed([
            'rows' => $data,
        ]);
    }

    public function optimize(Request $request)
    {
        $request->validate(['table' => 'required|array']);
        $tables = implode('`,`', $request->get('tables'));
        if (DB::statement("OPTIMIZE TABLE `".$tables."`")) {
            $this->CreateSyslog('优化数据表', $tables);
            return $this->succeed();
        }
        return $this->error();
    }

    public function repair(Request $request)
    {
        $request->validate(['table' => 'required|array']);
        $tables = implode('`,`', $request->get('tables'));
        if (DB::statement("REPAIR TABLE `".$tables."`")) {
            $this->CreateSyslog('修复数据表', $tables);
            return $this->succeed();
        }
        return $this->error();
    }

    public function clear(Request $request)
    {
        $request->validate(['table' => 'required']);
        $table = filterStr($request->get('table'));
        if (DB::statement("TRUNCATE TABLE `".$table."`")) {
            $this->CreateSyslog('清空数据表', $table);
            return $this->succeed();
        }
        return $this->error();
    }

    public function destroy(Request $request)
    {
        $request->validate(['table' => 'required']);
        $table = filterStr($request->get('table'));
        if (DB::statement("DROP TABLE `".$table."`")) {
            $this->CreateSyslog('删除数据表', $table);
            return $this->succeed();
        }
        return $this->error();
    }
}
